/*
 * @Date         : 2024-05-14 09:30:19 星期2
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"

export const appendAuthorization = (options, nextCall) => {
  const requester = new grpc.RequesterBuilder()
    .withStart((metadata, listener, next) => {
      metadata.set("Authorization", "Bearer some-secret-token1111111")
      next(metadata, listener)
    })
    .build()

  return new grpc.InterceptingCall(nextCall(options), requester)
}

export const validateAuthorization = (methodDescriptor, call) => {
  const listener = new grpc.ServerListenerBuilder()
    .withOnReceiveMetadata((metadata, next) => {
      if (validateAuthorizationMetadata(metadata)) {
        next(metadata)
      } else {
        call.sendStatus({
          code: grpc.status.UNAUTHENTICATED,
          details: "Authorization metadata not correct",
        })
      }
    })
    .build()

  const responder = new grpc.ResponderBuilder()
    .withStart((next) => next(listener))
    .build()

  return new grpc.ServerInterceptingCall(call, responder)
}

// 实际业务可用 jwt 生成和校验 token
function validateAuthorizationMetadata(metadata) {
  const authorization = metadata.get("Authorization")

  if (authorization.length < 1) return false
  return authorization[0] === "Bearer some-secret-token"
}
